#include "FrameBufferObject.h"

#include <iostream>

// shorter to type
void FrameBufferObject::enable()
{
  glBindFramebuffer(GL_FRAMEBUFFER, m_fboId);
}
void FrameBufferObject::disable()
{
  glBindFramebuffer(GL_FRAMEBUFFER, 0); // switch back to window-system-provided framebuffer
}

// create a frame buffer object
void FrameBufferObject::init()
{
  glGenFramebuffers(1, &m_fboId);
  
  //doAssembly();
  //checkStatus();
}

void FrameBufferObject::checkStatus()
{
	// check FBO status, one of these:
	//GL_FRAMEBUFFER_COMPLETE
	//GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT
	//GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT
	//GL_FRAMEBUFFER_INCOMPLETE_DUPLICATE_ATTACHMENT
	//GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT
	//GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT
	//GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT
	//GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT
	//GL_FRAMEBUFFER_UNSUPPORTED <- try a different combination
	//GL_FRAMEBUFFER_STATUS_ERROR

  GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
  if(status != GL_FRAMEBUFFER_COMPLETE){
      isComplete = false;
			std::cout << "FBO: fail" << std::endl;
  }else{
      isComplete = true;
  }
}

void FrameBufferObject::attachTexture(GLuint textureId)
{
	// attach the texture to FBO color attachment point
	// GL_COLOR_ATTACHMENTn. DEPTH_ATTACHMENT or STENCIL_ATTACHMENT
  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
                            GL_TEXTURE_2D, textureId, 0);
  checkStatus();
}
void FrameBufferObject::attachRenderBuffer(GLuint rboId)
{
  // attach the render buffer to depth attachment point
  glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
                               GL_RENDERBUFFER, rboId);
  checkStatus();
}


